package cn.middle.remote.handler.decodec;

import java.util.List;

import cn.middle.remote.message.HeartbeatPongSignal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class HeartbeatPongSignalCodec implements Codec<HeartbeatPongSignal> {

	private int mutableLength = 4 + 4;
	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		if (in.readableBytes() < mutableLength) {
			in.readerIndex(beginIndex);
			return;
		}

		int msgLength = in.readInt();

		if (!CodecUtil.checkLength(in, msgLength + 4, beginIndex)) {
			return;
		}
		
		String msgId = CodecUtil.context(in, msgLength);
		int pingLength = in.readInt();
		if (!CodecUtil.checkLength(in, pingLength, beginIndex)) {
			return;
		}
		
		String ping = CodecUtil.context(in, pingLength);
		if(!ping.equals(HeartbeatPongSignal.PONG)) {  //不是正确的心跳，关闭
			ctx.close();
			return ;
		}
		
		out.add(new HeartbeatPongSignal(msgId));
		
	}

	@Override
	public void encode(ChannelHandlerContext ctx, HeartbeatPongSignal msg, ByteBuf out) throws Exception {
		out.writeBytes(msg.toData());
		
	}

}
